<?php
/**
 * 蜗牛博客
 * 本文件内代码属于“蜗牛博客”项目，禁止修改再发布本程序源码，禁止去除页面底部的版权申明。所有版权保留
 * User: upliu
 * Email: 753073861@qq.com
 * QQ: 753073861
 * 程序主页：http://demo.upliu.net/snail-blog/
 */

require __DIR__ . '/init.php';

if (!is_installed()) {
    redirect_path('install.php');
}

$db = Db::getInstance();

$page_size = 5;

if ($tag_id = get('tag_id')) {
    $count = $db->queryColumn("select count(1) from post join map_post_tag on post.id=map_post_tag.post_id where tag_id=?", $tag_id);
    $offset = (get('_page', 1) - 1) * $page_size;
    $pagination = pagination('', $count, $page_size, '');
    $items = $db->queryAll("select post.* from post join map_post_tag on post.id=map_post_tag.post_id where tag_id=? limit $offset,$page_size", $tag_id);
    $data = array(
        'items' => $items,
        'pagination' => array(
            'html' => $pagination,
            'count' => $count
        ),
    );
} else {
    if ($m = get('m')) {
        $s = $m . '-01 00:00:00';
        $e = $m . '-31 23:59:59';
    } else {
        $s = $e = '';
    }

    $where = array(
        'category_id' => get('cid'),
        'post_date >=' => $s,
        'post_date <=' => $e,
        'post_title like' => get('s'),
        'order by id desc'
    );

    $data = $db->getList('post', $where, $page_size);
}

$author_ids = array_unique(array_column($data['items'], 'post_author_id'));
$rows = $db->queryAllWhereIn("select id,nickname from user", 'id', $author_ids);
$users = array_index($rows, 'id', true);

$post_ids = array_column($data['items'], 'id');
$category_ids = array_unique(array_column($data['items'], 'category_id'));

$rows = $db->queryAllWhereIn('select id,name from category', 'id', $category_ids);
$category_name_map = array_column($rows, 'name', 'id');
$category_name_map[0] = '默认分类';

$rows = $db->queryAllWhereIn('select post_id,tag_id from map_post_tag', 'post_id', $post_ids);
$post_tags = array_index($rows, 'post_id');
$tag_ids = array_column($rows, 'tag_id');

$rows = $db->queryAllWhereIn('select id,name from tag', 'id', $tag_ids);
$tag_name_map = array_column($rows, 'name', 'id');

foreach ($data['items'] as &$post) {

    if (!empty($post_tags[$post['id']])) {
        $post['tag'] = implode('、', array_map(function($pt) use ($tag_name_map){
            $tag_id = $pt['tag_id'];
            return "<a href='?tag_id=$tag_id'>".hsc($tag_name_map[$tag_id])."</a>";
        }, $post_tags[$post['id']]));
    } else {
        $post['tag'] = '';
    }

} unset($post);

echo renderWithLayout('index', array(
    'data' => $data,
    'users' => $users,
    'category_name_map' => $category_name_map
));